package il.ac.tau.dbcourse.db.reports;

import il.ac.tau.dbcourse.db.annotations.SQLReport;

import java.lang.annotation.Annotation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public abstract class AbsReport {

	protected Connection conn;
	private PreparedStatement insertStmt;
	private boolean isClosed = false;
	private Integer counter = 0;

	private List<Long> ids=new ArrayList<Long>();
	public AbsReport() {
		super();
	}

	private String getSQLTable() {
		Annotation anno = this.getClass().getAnnotation(SQLReport.class);
		if (anno != null) {
			SQLReport sqlReport = (SQLReport) anno;
			if (sqlReport.table().compareTo("") != 0) {
				return sqlReport.table();
			}
		}
		return "";
	}

	private String getSQLColumn() {
		Annotation anno = this.getClass().getAnnotation(SQLReport.class);
		if (anno != null) {
			SQLReport sqlReport = (SQLReport) anno;
			if (sqlReport.column().compareTo("") != 0) {
				return sqlReport.column();
			}
		}
		return "";
	}

	protected void createStmt() throws SQLException {
		insertStmt=conn.prepareStatement("INSERT INTO "+getSQLTable()+" ("+getSQLColumn()+") VALUES (?)");
	}

	public void truncate() throws SQLException {
		Statement stmt=conn.createStatement();
		stmt.execute("TRUNCATE TABLE "+getSQLTable());
	}

	public void insertId(Long id) throws SQLException {
		if (ids.contains(id)) return;
		insertStmt.setLong(1, id);
		insertStmt.addBatch();
		ids.add(id);
		counter++;
		if (counter>500) {
			flush();
			counter-=500;
		}
	}

	private void flush() throws SQLException {
		insertStmt.executeBatch();
	}

	public void close() throws SQLException {
		flush();
		insertStmt.close();
		conn=null;
		isClosed=true;
	}

	public boolean isClosed() {
		return isClosed;
	}

}